import os
import re

import redis



def get_datas(table_name, path, win_conn=None, db_conn=None):
    '''
    获取视图或表数据
    :param table_name: 表或视图名(例如：dbo_表名， View_视图名)
    :param path: 远程主机cube路径
    :param win_conn: 远程主机连接（如本机不传）
    :param db_conn: cube使用数据库连接（必要）
    :return:
    '''
    redis_conn = redis.Redis(host='127.0.0.1', port=6379, db=12)
    if win_conn:
        redis_key = "{}-{}-dsv-fields".format(win_conn.host, path)
        if not redis_conn.get(redis_key):
            file_names = win_conn.get_files('*.dsv.xml', path)
            content = ''
            for file_name in file_names:
                if 'dsv' in file_name:
                    content = win_conn.get_file_connect(file_name, path)
            redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
        else:
            content = redis_conn.get(redis_key).decode('utf-8')
    else:
        redis_key = "localhost-{}-dsv-fields".format(path)
        if not redis_conn.get(redis_key):
            file_name = ""  # 定义要读取的文件名变量
            for root, dirs, files in os.walk(path):
                for file in files:
                    if ".dsv.xml" in file:
                        file_name = file
            # 读取文件内容
            file_path = "{}/{}".format(path, file_name)
            content = ""
            with open(file_path, 'r') as rf:
                content = rf.read()
                rf.close()
            redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
        else:
            content = redis_conn.get(redis_key).decode('utf-8')
    redis_conn.close()
    # 按<>匹配，找到量值名称所在<>
    pat = re.compile('<xs:element name="{}(.*?)msprop:QueryBuilder="SpecificQueryBuilder">'.format(table_name))
    content_list = pat.findall(content.replace('\r\n', ''))
    # 新策略
    sql_pat = re.compile('msprop:QueryDefinition="(.*)"')
    sql = ""

    if 'dbo_' not in table_name:
        for item in content_list:
            sql = sql_pat.findall(
                # 替换掉所有特殊符号
                item.replace('&#xD;&#xA;', ' ').replace('\r\n', ' ').replace("&lt;", '<').replace('&gt;', '>'))[0]
        fields = db_conn.get_dict_datas(sql)
        return fields
    else:
        replace_table_name = table_name.replace('dbo_', 'dbo.')
        sql = 'select * from {}'.format(replace_table_name)
        fields = db_conn.get_dict_datas(sql)
        return fields


if __name__ == '__main__':
    from app_cube.utils.connect.my_db import MyDB
    path = r'C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data\YWC_SSAS.0.db'
    db_conn = MyDB('sqlserver', '127.0.0.1', 1433, 'sa', '123456', 'YWC_DW')
    result = get_datas(table_name="View_Fact_Inhosp_Fee_Detail", path=path, db_conn=db_conn)
    print(result)